package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.BsSysConfigConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 */
@Service
@Slf4j
public class BsSysConfigService {

    @Resource
    private ISysDictDataService dictDataService;


    @Transactional
    public void sysStyleUpdate(Long dictCode) {
        //取消默认 其他整体风格配置
        dictDataService.getBaseMapper().update(null, new UpdateWrapper<SysDictData>().lambda()
                .set(SysDictData::getIsDefault, BsSysConfigConstants.IS_DEFAULT_N)
                .eq(SysDictData::getDictType, BsSysConfigConstants.SYS_STYLE));
        //取消默认 其他整体风格配置
        dictDataService.getBaseMapper().update(null, new UpdateWrapper<SysDictData>().lambda()
                .set(SysDictData::getIsDefault, BsSysConfigConstants.IS_DEFAULT_Y)
                .eq(SysDictData::getDictCode, dictCode));
    }

    /**
     * 说明 : 关键词典-检查
     */
    public boolean allowBySysSecretWord(String msg) {
        if (StrUtil.isNotBlank(msg)) {
            SysDictData sysDictData = new SysDictData();
            sysDictData.setDictType(BsSysConfigConstants.SYS_SECRET_WORD);
            PageHelper.startPage(1, 1);
            List<SysDictData> list = dictDataService.selectDictDataList(sysDictData);
            long total = new PageInfo(list).getTotal();
            int totalPage = (int) Math.ceil((double) total / Constants.DEFAULT_ASYNC_PAGE_SIZE);
            log.info("关键词总量{},分页数:{},需累计循环比较次数:{}", total, Constants.DEFAULT_ASYNC_PAGE_SIZE, totalPage);
            ExecutorService executorService = Executors.newFixedThreadPool(5);
            CountDownLatch latch = new CountDownLatch(totalPage);
            ArrayList<SysDictData> illegalityList = new ArrayList<>();
            for (int i = 1; i <= totalPage; i++) {
                int finalPageNum = i;
                executorService.submit(() -> {
                    log.info("{}第{}次比对执行", Thread.currentThread().getName(), finalPageNum);
                    PageHelper.startPage(finalPageNum, Constants.DEFAULT_ASYNC_PAGE_SIZE);
                    List<SysDictData> pageList = dictDataService.selectDictDataList(sysDictData);
                    pageList.forEach(f -> {
                        if (msg.contains(f.getDictLabel())) {
                            illegalityList.add(f);
                        }
                    });
                    log.info("{}第{}次比对执行完成", Thread.currentThread().getName(), finalPageNum);
                    latch.countDown();
                });
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (!illegalityList.isEmpty()) {
                CompletableFuture.runAsync(() -> {
                    illegalityList.forEach(f -> {
                        try {
                            f.setRemark(String.valueOf((Integer.parseInt(f.getRemark()) + 1)));
                        } catch (Exception e) {
                            f.setRemark("1");
                        }
                        dictDataService.getBaseMapper().update(null, new UpdateWrapper<SysDictData>().lambda()
                                .set(SysDictData::getRemark, f.getRemark())
                                .eq(SysDictData::getDictCode, f.getDictCode()));
                    });
                });
                return false;
            }
        }
        return true;
    }

    public boolean sysSecretWordAdd(String dictLabel) {
        List<SysDictData> existList = dictDataService.getBaseMapper().selectList(new QueryWrapper<SysDictData>().lambda()
                .eq(SysDictData::getDictType, BsSysConfigConstants.SYS_SECRET_WORD)
                .eq(SysDictData::getDictLabel, dictLabel)
        );
        Assert.isTrue(existList.isEmpty(), "该关键词已存在！");
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictSort(BsSysConfigConstants.DEFAULT_SORT);
        sysDictData.setDictLabel(dictLabel);
        sysDictData.setDictValue(dictLabel);
        sysDictData.setDictType(BsSysConfigConstants.SYS_SECRET_WORD);
        sysDictData.setCssClass(StrUtil.EMPTY);
        sysDictData.setListClass(StrUtil.EMPTY);
        sysDictData.setIsDefault(BsSysConfigConstants.IS_DEFAULT_N);
        sysDictData.setStatus(BsSysConfigConstants.STATUS);
        sysDictData.setRemark(BsSysConfigConstants.DEFAULT_REMARK);
        return dictDataService.insertDictData(sysDictData) == 1;
    }

    public boolean sysSecretWordDel(String dictCode) {
        return dictDataService.removeById(dictCode);
    }
}




